<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="搜索内容" prop="searchContent">
        <el-input
          v-model="queryParams.searchContent"
          placeholder="请输入场站名称或场站ID"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-select
          v-model="queryParams.enable"
          placeholder="场站状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled = "multiple"
          @click="handleCopyAdd"
        >复制新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handlePeakValley"
        >尖峰平谷
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="true"
          @click="handleUpdate"
        >聚合数据
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <!-- 自增序号列 -->
      <el-table-column type="index" label="序号">
        <!-- 自定义索引 (可选) -->
        <template slot-scope="scope">
          {{ serial_number + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="场站编号" align="center" key="stationId" prop="stationId" v-if="columns[0].visible"
                       width="200"/>
      <el-table-column label="场站名称" align="center" key="stationName" prop="stationName" v-if="columns[1].visible">
        <template slot-scope="scope">
          <router-link :to="'/system/point/list/index/' + scope.row.stationId" class="link-type">
            <span>{{ scope.row.stationName }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="场站别名" align="center" key="stationAlias" prop="stationAlias" v-if="columns[2].visible"/>
      <el-table-column label="默认系数" align="center" key="factor" prop="factor" v-if="columns[3].visible" width="100"/>
      <el-table-column label="默认偏移量" align="center" key="constant" prop="constant" v-if="columns[4].visible"
                       width="100"/>
      <el-table-column label="默认表达式" align="center" key="expression" prop="expression" v-if="columns[5].visible"
                       width="200"/>
      <el-table-column label="电池簇数" align="center" key="clusterNum" prop="clusterNum" v-if="columns[6].visible" width="120"/>
      <el-table-column label="簇电池组数" align="center" key="packNum" prop="packNum" v-if="columns[7].visible" width="120"/>
      <el-table-column label="簇单体数" align="center" key="cellNum" prop="cellNum" v-if="columns[8].visible" width="120"/>
      <el-table-column label="状态" align="center" key="enable" v-if="columns[9].visible">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[10].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="250"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.stationId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            size="mini"
          >
            <router-link :to="'/system/cell-type-list/index/' + scope.row.id" class="link-type">
              单体类型
            </router-link>
          </el-button>
          <el-button
            type="text"
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport(scope.row.stationId)"
          >导入点表
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场站配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="场站ID" prop="stationId">
              <el-input v-model="form.stationId" placeholder="请输入场站ID" maxlength="32"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站名称" prop="stationName">
              <el-input v-model="form.stationName" placeholder="请输入场站名称" maxlength="64"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="场站别名" prop="stationAlias">
              <el-input v-model="form.stationAlias" type="text" placeholder="请输入场站别名" maxlength="32"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表达式" prop="expression">
              <el-input v-model="form.expression" type="text" placeholder="请输入表达式" maxlength="32"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="系数" prop="factor">
              <el-input v-model="form.factor" type="number" min="0" placeholder="请输入系数" maxlength="32"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="偏移量" prop="constant">
              <el-input v-model="form.constant" type="number" min="0" placeholder="请输入偏移量" maxlength="32"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电池簇数" prop="clusterNum">
              <el-input v-model="form.clusterNum" type="number" min="0" placeholder="请输入电池簇数" maxlength="32"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="簇电池组数" prop="packNum">
              <el-input v-model="form.packNum" type="number" min="0" placeholder="请输入簇电池组数" maxlength="32"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="簇单体数" prop="cellNum">
              <el-input v-model="form.cellNum" type="number" min="0" placeholder="请输入簇单体数" maxlength="32"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启动状态" prop="email">
              <el-switch v-model="form.enable" :loading="loading" activeValue="yes" inactiveValue="no" width="40"
                         active-text="开启" inactive-text="关闭"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 尖峰平谷配置对话框 -->
    <el-dialog :title="title" :visible.sync="peakValleyOpen" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label="操作时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 300px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?stationId='+upload.stationId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listStation,
  getStationDetail,
  delStation,
  addStation,
  updateStation,
  changeStationStatus, batchDelStation
} from "@/api/system/station/station";
import {getToken} from "@/utils/auth";

export default {
  name: "Station",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      stationList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 尖峰平谷显示弹出层
      peakValleyOpen: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        //场站Id
        stationId: '',
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/station/importPointData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchContent: '',
        onlineEnable: ''
      },
      // 列信息
      columns: [
        {key: 0, label: `场站编号`, visible: true},
        {key: 1, label: `场站名称`, visible: true},
        {key: 2, label: `场站别名`, visible: true},
        {key: 3, label: `系数`, visible: true},
        {key: 4, label: `偏移量`, visible: true},
        {key: 5, label: `表达式`, visible: true},
        {key: 6, label: `电池簇数`, visible: true},
        {key: 7, label: `簇电池组数`, visible: true},
        {key: 8, label: `簇单体数`, visible: true},
        {key: 9, label: `状态`, visible: true},
        {key: 10, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {
        stationId: [
          {required: true, message: "场站编号不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '场站编号长度必须介于 2 和 32 之间', trigger: 'blur'}
        ],
        stationName: [
          {required: true, message: "场站名称不能为空", trigger: "blur"}
        ],
        stationAlias: [
          {required: true, message: "场站别名不能为空", trigger: "blur"}
        ],
        clusterNum: [
          {required: true, message: "电池簇数不能为空", trigger: "blur"}
        ],
        packNum: [
          {required: true, message: "簇电池组数不能为空", trigger: "blur"}
        ],
        cellNum: [
          {required: true, message: "簇单体数不能为空", trigger: "blur"}
        ]
      }
    };
  },
  computed: {
    serial_number() {
      return this.queryParams.pageSize * (this.queryParams.pageNum - 1);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询场站列表 */
    getList() {
      this.loading = true;
      listStation(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.stationList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 场站状态修改
    handleStatusChange(row) {
      let text = row.enable === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.stationName + '"场站吗？').then(()=> {
        return changeStationStatus(row.id, row.enable);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.enable = row.enable === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.peakValleyOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        stationId: undefined,
        stationName: undefined,
        onlineEnable: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场站";
    },
    handleCopyAdd(){
      const ids = this.ids;
      if (ids.length > 1){
        this.$modal.msgWarning("只能选择一条数据");
        return;
      }
      const id = ids[0];
      this.disabled = false;
      this.reset();
      getStationDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "新增场站";
        this.form.id = undefined;
      });

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getStationDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改场站";
      });
    },
    handlePeakValley(){
      const ids = this.ids;
      this.peakValleyOpen = true;

    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleImport(stationId) {
      this.upload.title = "点表导入";
      this.upload.open = true;
      this.upload.stationId = stationId;
    },
    /**下载模板**/
    importTemplate() {
      this.upload.title = "下载模板";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除场站"' + row.stationName + '"的数据项？').then(function () {
        return delStation(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleBatchDelete() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return batchDelStation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  },
  async beforeChange(currentVal) {
    this.loading = true;
    return this.$confirm(`此操作将改变为<span style="color: #${!currentVal ? '409EFF' : 'F56C6C'};"> ${!currentVal} </span>状态，是否继续？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }).catch(() => {
      this.loading = false;
      return Promise.reject("cancel");
    });
  },
  change(val) {
    setTimeout(() => {
      this.$message.success('switch success' + val);
      this.loading = false;
    }, 1500)
  },
  // 更多操作触发
  handleCommand(command, row) {
    switch (command) {
      case "settingPackCell":
        this.settingPackCell(row);
        break;
      case "settingCellType":
        this.settingCellType(row);
        break;
      // case "importPointData":
      //   this.importPointData(row);
      //   break;
      default:
        break;
    }
  },
  /** 设置电池组单体 */
  settingPackCell(row) {
    // this.reset();
    this.$router.push(`system/station/pack-cell-list`)
  },
  /** 设置单体类型 */
  settingCellType(row) {
    // this.reset();
    this.$router.push(`system/station/cell-type-list`)
  },

  /** 导入点表操作 */
  // importPointData() {
  //   this.upload.title = "点表导入";
  //   this.upload.open = true;
  //
  //   // const stationIds = row.stationId || this.ids;
  //   // this.$modal.confirm('是否确认删除场站编号为"' + stationIds + '"的数据项？').then(function () {
  //   //   return handleImportPointData(stationIds);
  //   // }).then(() => {
  //   //   this.getList();
  //   //   this.$modal.msgSuccess("删除成功");
  //   // }).catch(() => {
  //   // });
  // }

};
</script>
